package com.quanyan.stadium.service.gameEvent.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.quanyan.club.entity.RespClubPlainInfo;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.utils.ObjectUtil;
import com.quanyan.common.vo.Image;
import com.quanyan.place.entity.apiresp.RespCity;
import com.quanyan.place.entity.apiresp.RespCityInfos;
import com.quanyan.place.entity.apiresp.RespDistrict;
import com.quanyan.stadium.api.req.ReqChallenge;
import com.quanyan.stadium.api.req.gameEventConfig.ReqClubCreateGameEvent;
import com.quanyan.stadium.api.req.v2.ReqClubGameEvent;
import com.quanyan.stadium.api.req.v3.ReqGameRoundV2;
import com.quanyan.stadium.api.resp.RespGameEventDetail;
import com.quanyan.stadium.api.resp.v2.*;
import com.quanyan.stadium.biz.BizGameOrderDao;
import com.quanyan.stadium.biz.BizGameSystemDao;
import com.quanyan.stadium.component.pushMsg.MsgPush;
import com.quanyan.stadium.constants.GameConstants;
import com.quanyan.stadium.entity.*;
import com.quanyan.stadium.entity.vo.*;
import com.quanyan.stadium.enums.ErrorEnum;
import com.quanyan.stadium.enums.GameCategoryConfigEnum;
import com.quanyan.stadium.enums.GameSystemConfigEnum;
import com.quanyan.stadium.enums.GameTypeConfigEnum;
import com.quanyan.stadium.mapper.*;
import com.quanyan.stadium.service.GameEventService;
import com.quanyan.stadium.service.commonComponent.BaseService;
import com.quanyan.stadium.service.commonComponent.GameMsgPush;
import com.quanyan.stadium.service.commonComponent.OfficialGameCache;
import com.quanyan.stadium.service.gameEvent.ClubGameEventConfigService;
import com.quanyan.stadium.service.gameRules.GameRoundService;
import com.quanyan.stadium.service.gameRules.GameScheduleService;
import com.quanyan.stadium.service.gameSign.GameSignUpService;
import com.quanyan.stadium.transfer.GameConfigTransfer;
import com.quanyan.stadium.utils.GameUtils;
import com.quanyan.statium.api.req.GameCategory;
import com.quanyan.user.response.RespUserInfoBase;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.filefilter.FalseFileFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * Created by xiaoxiao on 16/10/9.
 *
 * 俱乐部赛事的创建
 */
@Service
public class ClubGameEventConfigServiceImpl implements ClubGameEventConfigService {

    private static final Logger logger = LoggerFactory.getLogger(ClubGameEventConfigServiceImpl.class);

    @Autowired
    private BaseService baseService;

    @Autowired
    private BizGameSystemDao bizGameSystemDao;

    @Autowired
    private OfficialGameCache officialGameCache;

    @Autowired
    private GameRoundService gameRoundService;

    @Autowired
    private VStadiumUserDefinedMapper vStadiumUserDefinedMapper;

    @Autowired
    private GameScheduleService gameScheduleService;

    @Autowired
    private GameConfigTransfer gameEventTransfer;

    @Autowired
    private GameSignUpService gameSignUpService;

    @Autowired
    private GameMsgPush gameMsgPush;

    @Autowired
    private GameEventService gameEventService;

    @Autowired
    private BizGameOrderDao bizGameOrderDao;

    @Autowired
    TbGameRoundMapper tbGameRoundMapper;

    @Autowired
    TbGameEventTeamMapper tbGameEventTeamMapper;

    @Autowired
    TbGameScheduleMapper tbGameScheduleMapper;

    @Autowired
    TbGameScheduleAddendumMapper tbGameScheduleAddendumMapper;

    @Value("${share.server.name}")
    private String shareServerName;

    @Override
    public GameEvent createGameEvent(ReqClubCreateGameEvent reqClubCreateGameEvent, int uid) throws Exception {
        if (reqClubCreateGameEvent.getTeamLimitNum() > 1024) {
            throw new BizException(null, "报名人数或队伍数不能超过1024");
        }
        List<Integer> uIds = baseService.getManageByClubId(reqClubCreateGameEvent.getClubId());
        if (CollectionUtils.isEmpty(uIds) || !uIds.contains(uid)) {
            throw new BizException(null, "只有该俱乐部创建者才能创建比赛");
        }
        GameCategory gameCategory = gameEventTransfer.getGameCategoryById(reqClubCreateGameEvent.getGameCategoryType().intValue());
        if (reqClubCreateGameEvent.getGameSystemType().intValue() == GameSystemConfigEnum.CONFIG_GAME_TYPE_MIXED.getId()) {
            if (gameCategory.getMinNum().intValue() == gameCategory.getMaxNum().intValue() && gameCategory.getMinNum().intValue() == 2) {
                throw new BizException(null, "混合制暂不支持双打");
            }
        }

        /**
         * 双打人数判断
         */
        if(gameCategory.getMinNum().intValue() == gameCategory.getMaxNum().intValue() && gameCategory.getMinNum().intValue() == 2){
           if(reqClubCreateGameEvent.getTeamLimitNum() % 2 != 0){
               throw new BizException(null,"双打人数必须为偶数！");
           }
        }

        TbGameEvent tbGameEvent = new TbGameEvent();
        tbGameEvent.setPrice(reqClubCreateGameEvent.getPrice());
        tbGameEvent.setStartTime(new Date(reqClubCreateGameEvent.getStartTime()));
        tbGameEvent.setEndTime(new Date(reqClubCreateGameEvent.getEndTime()));
        tbGameEvent.setSignStartTime(new Date());
        tbGameEvent.setSignEndTime(new Date(reqClubCreateGameEvent.getStartTime()));
        if (reqClubCreateGameEvent.getSignEndTime() > 0) {
            tbGameEvent.setSignEndTime(new Date(reqClubCreateGameEvent.getSignEndTime()));
        }
        tbGameEvent.setCategoryId(reqClubCreateGameEvent.getCategoryId());
        tbGameEvent.setType(GameConstants.CLUB_CREATE);
        tbGameEvent.setUid(uid);
        tbGameEvent.setClubId(reqClubCreateGameEvent.getClubId());
        tbGameEvent.setGameSystemType(reqClubCreateGameEvent.getGameSystemType().byteValue());
        tbGameEvent.setGameCategoryType(reqClubCreateGameEvent.getGameCategoryType());
        tbGameEvent.setGameGradeLevelType(reqClubCreateGameEvent.getGameGradeLevel());

        //TODO  小球内部赛\大球非内部赛
        if (reqClubCreateGameEvent.getCategoryId().intValue() == GameConstants.CATEGORY_ID_FOOTBALL || reqClubCreateGameEvent.getCategoryId().intValue() == GameConstants.CATEGORY_ID_BASKETBALL) {
            tbGameEvent.setGameEventType((byte) GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_BIG.getId());
        }else {
            tbGameEvent.setGameEventType((byte) GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_INTERNAL.getId());
        }
        tbGameEvent.setIsVisible(reqClubCreateGameEvent.getIsVisible().byteValue());
        tbGameEvent.setGameDesc(reqClubCreateGameEvent.getComments());
        tbGameEvent.setManagerMobile(reqClubCreateGameEvent.getHostMobile());
        tbGameEvent.setPayType(reqClubCreateGameEvent.getPayType());

        if (tbGameEvent.getCategoryId() == GameConstants.CATEGORY_ID_FOOTBALL ||
                tbGameEvent.getCategoryId() == GameConstants.CATEGORY_ID_BASKETBALL) {
            tbGameEvent.setGameTeamType(GameConstants.IS_DELETE);
        }
        if (reqClubCreateGameEvent.getTeamLimitNum() == 0) {
            tbGameEvent.setTeamLimitNum(Integer.MAX_VALUE);
            tbGameEvent.setInventoryLevel(Integer.MAX_VALUE);
        }else {
            tbGameEvent.setTeamLimitNum(reqClubCreateGameEvent.getTeamLimitNum());
            tbGameEvent.setInventoryLevel(reqClubCreateGameEvent.getTeamLimitNum());
        }

        Gson gson =new Gson();
        RespClubPlainInfo club = baseService.queryClubMsg(reqClubCreateGameEvent.getClubId());
        if (null == club || club.getClubId() < 1) {
            throw new BizException(null, "该俱乐部不存在");
        }
        MultiMedia multiMedia = new MultiMedia();
        Image image = new Image();
        if (StringUtils.isEmpty(reqClubCreateGameEvent.getImage())) {
            image.setImageUrl(club.getLogo());
            List<TbGamePoster> posters = bizGameSystemDao.queryTbGamePosterList(reqClubCreateGameEvent.getCategoryId());
            if (CollectionUtils.isNotEmpty(posters)) {
                image.setImageUrl(posters.get(new Random().nextInt(posters.size())).getUrl());
            }
        }else {
            image.setImageUrl(reqClubCreateGameEvent.getImage());
        }
        tbGameEvent.setManagerName(club.getClubName());
        multiMedia.setType(GameConstants.IS_NOT_DELETE);   //图片
        multiMedia.setImage(image);
        tbGameEvent.setMultiMedia(gson.toJson(multiMedia));
        String gameCode = GameUtils.generateGameCode((byte) GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_NGKC.getId(), reqClubCreateGameEvent.getCategoryId(), 0, reqClubCreateGameEvent.getGameSystemType().byteValue());
        tbGameEvent.setGameNumber(gameCode);
        if (!StringUtils.isEmpty(reqClubCreateGameEvent.getName())) {
            tbGameEvent.setName(reqClubCreateGameEvent.getName());
        }else {
            tbGameEvent.setName(club.getClubName()+gameCode.substring(gameCode.length()-4));
        }

        RespDistrict respDistrict = this.initRespDistrict(reqClubCreateGameEvent.getLat(), reqClubCreateGameEvent.getLng(), reqClubCreateGameEvent.getPlaceId());
        tbGameEvent.setAddress(reqClubCreateGameEvent.getAddress());
        tbGameEvent.setCityId(respDistrict.getCityId());
        if (null!=respDistrict.getLat()) {
            tbGameEvent.setLat(reqClubCreateGameEvent.getLat());
        }
        if (null!=respDistrict.getLng()) {
            tbGameEvent.setLng(reqClubCreateGameEvent.getLng());
        }
        if (null!=respDistrict.getId()) {
            tbGameEvent.setDistrictId(respDistrict.getId());
        }
        if (null!=reqClubCreateGameEvent.getPlaceId()) {
            tbGameEvent.setPlaceId(reqClubCreateGameEvent.getPlaceId());
        }
        tbGameEvent = bizGameSystemDao.insertTbGameEvent(tbGameEvent);

        if (null == tbGameEvent.getId())
            new BizException(null, ErrorEnum.ERROR_DB.getLabel());
        logger.info("俱乐部创建赛事成功.俱乐部ID:{},赛事ID{}", reqClubCreateGameEvent.getClubId(), tbGameEvent.getId());
        GameEvent event = new GameEvent();
        event.setId(tbGameEvent.getId());
        event.setName(tbGameEvent.getName());
        event.setGameNumber(gameCode);

        if (reqClubCreateGameEvent.getCategoryId().intValue() == GameConstants.CATEGORY_ID_FOOTBALL || reqClubCreateGameEvent.getCategoryId().intValue() == GameConstants.CATEGORY_ID_BASKETBALL) {
            TbGameCommonParameter tbGameCommonParameter = baseService.queryTbGameCommonParameter(GameConstants.STADIUM_DEFAULT_GROUP_PARAMETER_KEY,
                    MsgPush.GAME_OFFICIAL_EVENT_SHARE_URL);
            event.setShareUrl(shareServerName + tbGameCommonParameter.getParameterValue());  //分享
        }else {
            TbGameCommonParameter tbGameCommonParameter = baseService.queryTbGameCommonParameter(GameConstants.STADIUM_DEFAULT_GROUP_BASE_CONFIG_KEY,
                    MsgPush.GAME_SCENE_EVENT_INTERNAL_DETAIL_SHARE_URL);
            event.setShareUrl(shareServerName + tbGameCommonParameter.getParameterValue());  //分享
        }
        return event;
    }

    public RespGameEventDetail gameEventDetail(Integer gameEventId, Integer uid) throws InvocationTargetException, IllegalAccessException {
        RespGameEventDetail result = new RespGameEventDetail();
        result.setIsAdmin(GameConstants.IS_NOT_DELETE);
        GameEvent tbGameEvent = officialGameCache.getGameEvent(gameEventId);
        TbGameEvent tb = bizGameSystemDao.selectTbGameEvent(gameEventId);
        try {
            BeanUtils.copyProperties(result, tbGameEvent);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        result.setCurrentTeamNum(tb.getTeamLimitNum()-tb.getInventoryLevel());
        if (uid!=null) {
            List<Integer> clubUids = baseService.getManageByClubId(tb.getClubId());
            List<Integer> clubIds = baseService.queryMyClubIds(uid);    //用户所在俱乐部id集合,用户具有特殊权限的俱乐部id
            List<TbGameEventTeam> teams = bizGameSystemDao.selectTbGameEventTeamByGameEventId(gameEventId, null, null, null);
            if (null !=teams && teams.size() >0) {
                for (TbGameEventTeam team : teams) {
                    if (tbGameEvent.getGameTeamType().intValue() == GameConstants.TEAM_TYPE_PERSON) {//个人
                        if (team.getUid().intValue() == uid.intValue()) {
                            result.setIsJoinAccess((byte) 1);
                            result.setIsJoin((byte) 1);
                            break;
                        }
                    }else if (tbGameEvent.getGameTeamType().intValue() == GameConstants.TEAM_TYPE_CLUB) { //俱乐部
                        if (null!=clubIds&&clubIds.size() >0 && clubIds.contains(team.getClubId())) {
                            result.setIsJoinAccess((byte) 1);
                            result.setIsJoin((byte) 1);
                            break;
                        }

                    }else {
                    }
                }
            }
            if (null!=clubUids && clubUids.size()>0 && clubUids.contains(uid)) {
                result.setIsAdmin(GameConstants.IS_DELETE);
            }
        }
        return result;
    }

    @Override
    public boolean isClubAuth(Integer clubId) {
        List<TbGameClubOfficial> tbGameClubOfficials = bizGameSystemDao.queryTbGameOfficialClubList(null, null);
        if (CollectionUtils.isNotEmpty(tbGameClubOfficials)) {
            for (TbGameClubOfficial tbGameClubOfficial : tbGameClubOfficials) {
                if (tbGameClubOfficial.getClubId().equals(clubId)) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public List<RespGameSchedule> openNextGameRoundV2(Integer gameEventId, Integer gameRoundId, Integer uid) throws Exception {
        List<RespGameSchedule> result = new ArrayList<>();
        ReqChallenge reqChallenge = new ReqChallenge();
        reqChallenge.setGameEventId(gameEventId);
        reqChallenge.setIsArrange(GameConstants.IS_NOT_DELETE);
        List<TbGameRound> tbGameRoundList = bizGameSystemDao.selectTbGameRoundByGameEventId(reqChallenge.getGameEventId());
        int waitGenerateGameRoundId = -1;
        for (int i=0;i<tbGameRoundList.size();i++) {
            if (tbGameRoundList.get(i).getId().intValue() == gameRoundId.intValue()) {
                if ((i+1) < tbGameRoundList.size()){
                    waitGenerateGameRoundId = tbGameRoundList.get(i+1).getId();
                    break;
                }
            }
        }
        reqChallenge.setGameRoundId(waitGenerateGameRoundId);
        Map<Integer, List<GameSchedule>> params = gameRoundService.generateCompListV2(reqChallenge);
        List<GameSchedule> temp = params.get(waitGenerateGameRoundId);
        for (GameSchedule schedule : temp) {
            RespGameSchedule re = new RespGameSchedule();
            re.setGameRoundId(waitGenerateGameRoundId);
            re.setId(schedule.getId());
            re.setHomeGameTeam(schedule.getHomeGameTeam());
            re.setAwayGameTeam(schedule.getAwayGameTeam());
            re.setIsWin(schedule.getIsWin());
            re.setRecordStatus(schedule.getRecordStatus());
            re.setScore(schedule.getScore());
            result.add(re);
        }
        return result;
    }

    @Override
    public RespClubGameDetail clubGameEventDetailV2(Integer gameEventId, Integer uid) {
        RespClubGameDetail detail = new RespClubGameDetail();
        detail.setIsMember(GameConstants.IS_DELETE);
        detail.setUserRole(GameConstants.IS_DELETE);
        //分享信息
        TbGameCommonParameter tbGameCommonParameter = baseService.queryTbGameCommonParameter(GameConstants.STADIUM_DEFAULT_GROUP_BASE_CONFIG_KEY,
                MsgPush.GAME_SCENE_EVENT_INTERNAL_DETAIL_SHARE_URL);
        detail.setShareUrl(shareServerName+tbGameCommonParameter.getParameterValue());
        TbGameEvent gameEvent = bizGameSystemDao.selectTbGameEvent(gameEventId);
        if (null == gameEvent || gameEvent.getId() < 1)
            return detail;
        /**
         * 能否编辑对手
         *
         * 条件：1.比赛处于第一轮（第一轮对阵表已生产）
         *      2.未录入任何比分
         *      3.该用户为创建比赛的管理员
         *      4.比赛为等位制
         */
        boolean isEditable = false;
        //查询赛事当前轮次状态
        int currentRoundId = gameEvent.getCurrentRoundId();
        TbGameRound tbGameRound = tbGameRoundMapper.selectByPrimaryKey(currentRoundId);

        //查询当前赛程比分录入状态
        boolean isRecord = false;
        if(currentRoundId > 0){
            TbGameScheduleExample scheduleExample = new TbGameScheduleExample();
            TbGameScheduleExample.Criteria criteria = scheduleExample.createCriteria();
            criteria.andGameRoundIdEqualTo(currentRoundId);
            List<TbGameSchedule> tbGameSchedules = tbGameScheduleMapper.selectByExample(scheduleExample);

//            /**
//             * 判断第一轮是否轮空，如果轮空，那么 isRecord == false
//             */
//            boolean isFirstRouldNull = false;
//            TbGameScheduleAddendumExample scheduleAddendumExample = new TbGameScheduleAddendumExample();
//            TbGameScheduleAddendumExample.Criteria criteria1 = scheduleAddendumExample.createCriteria();
//            criteria1.andGameScheduleIdEqualTo(tbGameSchedules.get(0).getId());
//            List<TbGameScheduleAddendum> tbGameScheduleAddendums = tbGameScheduleAddendumMapper.selectByExample(scheduleAddendumExample);
//            for (TbGameScheduleAddendum scheduleAddendum: tbGameScheduleAddendums){
//                if (null != scheduleAddendum.getEventTeamId() && scheduleAddendum.getEventTeamId() == 0){
//                    isFirstRouldNull = true;
//                    break;
//                }
//            }
//            /**
//             * 如果第一轮不轮空，则判断是否已经录入比分
//             */
//            if(!isFirstRouldNull){
//                for(TbGameSchedule schedule :tbGameSchedules){
//                    if(null != schedule.getFinalScore()){
//                        isRecord = true;
//                        break;
//                    }
//                }
//            }
            TbGameSchedule firstSchedule = tbGameSchedules.get(0);
           if(null != firstSchedule.getFinalScore() && firstSchedule.getFinalScore().equals("1:0") && firstSchedule.getCreateTime().getTime() == firstSchedule.getUpdateTime().getTime()){
               String finalScore2 = tbGameSchedules.get(1).getFinalScore();
               if(null != finalScore2){
                   isRecord = true;
               }
           }else{
               if(null != firstSchedule.getFinalScore()){
                   isRecord = true;
               }

           }

            if(null != tbGameRound){
                if(tbGameRound.getRoundStatus() == 1 && GameSystemConfigEnum.CONFIG_GAME_TYPE_SWISS.getId() == gameEvent.getGameSystemType() && !isRecord ){
                    isEditable = true;
                }
            }
        }
        List<Integer> uIds = baseService.getManageByClubId(gameEvent.getClubId());
        if (!uIds.contains(uid)) {
            detail.setUserRole(GameConstants.IS_NOT_DELETE);
            isEditable = false;
        }
        detail.setEditable(isEditable);
        logger.info("ClubGameEventConfigServiceImpl.clubGameEventDetailV2中数据,用户权限userRole:{}", detail.getUserRole());
        detail.setRespGameEventAbstract(initRespGameEventAbstract(gameEvent));
        queryJoinUser1(gameEventId, detail,uid);
        queryCurrentGameRound(gameEventId, uid, detail, gameEvent);
        return detail;
    }

    private void queryCurrentGameRound(Integer gameEventId, Integer uid, RespClubGameDetail detail, TbGameEvent gameEvent) {
        if (null != gameEvent.getCurrentRoundId()) {
            List<TbGameRound> gameRounds = bizGameSystemDao.selectTbGameRoundByGameEventId(gameEventId);
            List<RespGameRound> respGameRoundV2s = new ArrayList<>();
            if (gameRounds.size() > 0) {
                RespGameRound respGameRoundV2 = new RespGameRound();
                respGameRoundV2.setId(gameEvent.getCurrentRoundId());
                respGameRoundV2.setRoundType(gameEvent.getCurrentRoundId().intValue() == -1?gameRounds.size()-1:gameEvent.getCurrentRoundId() - gameRounds.get(0).getId());
                List<TbGameSchedule> tbGameSchedules = bizGameSystemDao.selectTbGameScheduleByGameRoundId(gameEvent.getCurrentRoundId(), 0, GameConstants.GAME_SCHEDULE_NUM);
                if (CollectionUtils.isNotEmpty(tbGameSchedules) && gameEvent.getCurrentRoundId() > 0) {
                    List<RespGameSchedule> v2s = new ArrayList<>();
                    for (TbGameSchedule schedule : tbGameSchedules) {
                        RespGameSchedule v2 = new RespGameSchedule();
                        GameSchedule gameScheduleTemp = null;
                        try {
                            gameScheduleTemp = officialGameCache.getGameSchedule(schedule.getId(), GameConstants.TEAM_TYPE_PERSON);
                            BeanUtils.copyProperties(v2, gameScheduleTemp);
                        } catch (Exception e) {
                            logger.error("GameSchedule对象转化为RespGameScheduleV2失败/获取当前赛程:"+schedule.getId()+"失败,原因:{}", e);
                            e.printStackTrace();
                        }
                        if (detail.getUserRole().intValue() == GameConstants.IS_DELETE.intValue()) {
                            v2.setRecordAuth(GameConstants.IS_DELETE);
                        }else {
                            if (uid > 0) {
                                Set<User> tempUser = new HashSet<>();
                                if (null!=gameScheduleTemp.getHomeGameTeam() && CollectionUtils.isNotEmpty(gameScheduleTemp.getHomeGameTeam().getUserList())) {
                                    tempUser.addAll(gameScheduleTemp.getHomeGameTeam().getUserList());
                                }
                                if (null!=gameScheduleTemp.getAwayGameTeam() && CollectionUtils.isNotEmpty(gameScheduleTemp.getAwayGameTeam().getUserList())) {
                                    tempUser.addAll(gameScheduleTemp.getAwayGameTeam().getUserList());
                                }
                                if (CollectionUtils.isNotEmpty(tempUser)) {
                                    for (User u : tempUser) {
                                        if (null != u.getUid() && u.getUid().intValue() == uid.intValue()) {
                                            v2.setRecordAuth(GameConstants.IS_DELETE);
                                            break;
                                        }
                                    }
                                }
                            }
                        }

                        v2s.add(v2);
                    }
                    respGameRoundV2.setGameScheduleV2s(v2s);
                    respGameRoundV2s.add(respGameRoundV2);
                }
            }
            detail.setRoundNum(gameRounds.size());
            detail.setRespGameRoundV2s(respGameRoundV2s);
        }
    }

    private void queryJoinUser1(Integer gameEventId, RespClubGameDetail detail, Integer uid) {
        List<User> users = new ArrayList<>();
        List<Integer> teamUids = vStadiumUserDefinedMapper.selectUidFromGameTeam(gameEventId);
        logger.info("ClubGameEventConfigServiceImpl中方法queryJoinUser1的teamUids:"+teamUids.size());
        boolean flag = false;
        if (CollectionUtils.isNotEmpty(teamUids)) {
            Map<Integer, RespUserInfoBase> paramMap = baseService.queryUserMsg(teamUids);
            if (null!=paramMap && paramMap.size()>0) {
                for (Map.Entry<Integer, RespUserInfoBase> temp : paramMap.entrySet()) {
                    User user = new User();
                    try {
                        BeanUtils.copyProperties(user, temp.getValue());
                    } catch (Exception e) {
                        logger.error("RespUserInfoBase转化user出错,原因:{}", e);
                    }
                    if (user.getUid().intValue() == uid.intValue()) {
                        flag =true;
                    }
                    users.add(user);
                }
            }
        }
        detail.setCurrentUserList(users);
        detail.setIsJoin(flag ? GameConstants.IS_DELETE : GameConstants.IS_NOT_DELETE);
    }


    private List<User> queryJoinUser(Integer gameEventId) {
        List<User> users = new ArrayList<>();
        List<Integer> teamUids = vStadiumUserDefinedMapper.selectUidFromGameTeam(gameEventId);
        if (CollectionUtils.isNotEmpty(teamUids)) {
            Map<Integer, RespUserInfoBase> paramMap = baseService.queryUserMsg(teamUids);
            if (null != paramMap && paramMap.size()>0) {
                for (Map.Entry<Integer, RespUserInfoBase> temp : paramMap.entrySet()) {
                    User user = new User();
                    try {
                        BeanUtils.copyProperties(user, temp.getValue());
                    } catch (Exception e) {
                        logger.error("RespUserInfoBase转化user出错,原因:{}", e);
                    }
                    users.add(user);
                }
            }
        }
        return users;
    }

    private RespGameEventAbstract initRespGameEventAbstract(TbGameEvent gameEvent) {
        RespGameEventAbstract eventAbstract = new RespGameEventAbstract();
        eventAbstract.setId(gameEvent.getId());
        eventAbstract.setCurrentGameRoundId(gameEvent.getCurrentRoundId());
        eventAbstract.setName(gameEvent.getName());
        eventAbstract.setCreateTime(gameEvent.getCreateTime().getTime());
        eventAbstract.setStartTime(gameEvent.getStartTime().getTime());
        eventAbstract.setCurrentTime(new Date().getTime());
        eventAbstract.setGameCategory(gameEventTransfer.getGameCategoryById(gameEvent.getGameCategoryType().intValue()));
        eventAbstract.setGameSystem(gameEventTransfer.getGameSystemById(gameEvent.getGameSystemType().intValue()));
        eventAbstract.setGameGradeLevel(gameEventTransfer.getGameGradeLevelById(gameEvent.getCategoryId(), gameEvent.getGameGradeLevelType().intValue()));
        eventAbstract.setAddress(gameEvent.getAddress());
        eventAbstract.setCategoryId(gameEvent.getCategoryId());
        eventAbstract.setLat(gameEvent.getLat());
        eventAbstract.setLng(gameEvent.getLng());
        eventAbstract.setPrice(gameEvent.getPrice());
        eventAbstract.setTeamLimitNum(gameEvent.getTeamLimitNum());
        eventAbstract.setSignEndTime(gameEvent.getSignEndTime().getTime());
        eventAbstract.setContactName(gameEvent.getManagerName());
        eventAbstract.setDesc(gameEvent.getGameDesc());
        eventAbstract.setContactMobile(gameEvent.getManagerMobile());
        eventAbstract.setMultiMediaType(new Gson().fromJson(gameEvent.getMultiMedia(), MultiMedia.class));
        eventAbstract.setClubId(gameEvent.getClubId());
        eventAbstract.setIsVisiable(gameEvent.getIsVisible());
        return eventAbstract;
    }

    @Override
    public List<RankGameTeam> clubGameEventRankList(Integer gameEventId, Integer uid) {
        List<RankGameTeam> result = new ArrayList<>();
        TbGameEvent gameEvent = bizGameSystemDao.selectTbGameEvent(gameEventId);





        if(gameEvent.getCurrentRoundId().intValue() == -1) {
            List<TbGameEventScore> tbGameEventScores = bizGameSystemDao.queryTbGameEventScoreList(gameEventId);
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(tbGameEventScores)) {
                try {
                    result = gameScheduleService.tbGameTeamTransferGameTeamV3(gameEvent, tbGameEventScores, GameConstants.TEAM_TYPE_PERSON);
                } catch (Exception e) {
                    logger.error("tbGameEventScore转化出错GameTeam,原因:{}", e);
                }
                Collections.sort(result, new Comparator<GameTeam>() {   //排名
                    public int compare(GameTeam o1, GameTeam o2) {
                        return o1.getRank().compareTo(o2.getRank());
                    }
                });
            }
        }else {
            if (gameEvent.getGameSystemType().intValue() == GameSystemConfigEnum.CONFIG_GAME_TYPE_EIGHT_RULE.getId()) {
                int lastRoundId = gameEvent.getCurrentRoundId();
                if (gameEvent.getCurrentRoundId() == -1) {
                    List<TbGameRound> tbGameRoundList = bizGameSystemDao.selectTbGameRoundByGameEventId(gameEventId);
                    lastRoundId = tbGameRoundList.get(tbGameRoundList.size()-1).getId();
                }
                List<TbGameSchedule> tbGameSchedules = bizGameSystemDao.selectTbGameScheduleByGameRoundId(lastRoundId, 0, GameConstants.GAME_SCHEDULE_NUM);
                if (CollectionUtils.isNotEmpty(tbGameSchedules) && gameEvent.getGameSystemType().intValue() == GameSystemConfigEnum.CONFIG_GAME_TYPE_EIGHT_RULE.getId()) {
                    TbGameSchedule schedule = tbGameSchedules.get(0);
                    List<TbGameEventTeam> teams = bizGameSystemDao.selectTbGameEventTeamByIds(new Gson().<List<Integer>>fromJson(schedule.getTeamListIndex(), new TypeToken<List<Integer>>() {
                    }.getType()));

                    //TODO 排序存在问题
                    try {
                        result = gameScheduleService.tbGameTeamTransferGameTeamV4(gameEvent, teams, GameConstants.TEAM_TYPE_PERSON);
                    } catch (Exception e) {
                        logger.error("tbGameEventTeam转化出错GameTeam,原因:{}", e);
                    }
                }
            }
        }
        return result;
    }

    @Override
    public void cancelClubGameEvent(Integer gameEventId, Integer uid) {
        TbGameEvent gameEvent = bizGameSystemDao.selectTbGameEvent(gameEventId);

        //判断是否为管理员
        List<Integer> uIds = baseService.getManageByClubId(gameEvent.getClubId());
        if (!uIds.contains(uid)) {
            throw new BizException(null,"您不是管理员，没有权限取消比赛");
        }

        if (null!=gameEvent.getCurrentRoundId()) {
            if(gameEvent.getCurrentRoundId().intValue() != 0) {
                if (gameEvent.getCurrentRoundId().intValue() == -1) {
                    throw new BizException(null, "赛事已经完结,无法取消比赛");
                }else {
                    throw new BizException(null, "赛事已处于进行中,无法取消比赛");
                }
            }
        }
        if (bizGameSystemDao.cancelGameEvent(gameEventId).getId() < 1) {
            throw  new BizException(null, "取消比赛失败");
        }
        try{
            gameSignUpService.refound(gameEventId);
        }catch (Exception e)  {
            logger.error("赛事退款失败, 当前赛事ID:{}", gameEventId);
        }
        logger.info("赛事取消调起退款流程,当前赛事Id:{}", gameEventId);

        List<TbGameEventTeam> totalTeams = bizGameSystemDao.selectTbGameEventTeamByGameEventId(gameEvent.getId(), GameConstants.IS_NOT_DELETE);

        if (totalTeams!=null && totalTeams.size() >0) {
            List<Integer> totalUids = new ArrayList<>();
            if (gameEvent.getGameTeamType().equals(GameConstants.TEAM_TYPE_CLUB)) {   //俱乐部
                List<Integer> clubIds = new ArrayList<>();
                for (TbGameEventTeam tb:totalTeams) {
                    clubIds.add(tb.getClubId());
                }
                Map<Integer ,List<Integer>> clugUIds = baseService.queryClubIds(clubIds);
                for (TbGameEventTeam tb:totalTeams) {
                    totalUids.addAll(clugUIds.get(tb.getClubId()));
                }
            }else { //个人
                for (TbGameEventTeam tb:totalTeams) {
                    totalUids.add(tb.getUid());
                }
            }
            if (totalUids!=null && totalUids.size()>0) {    //推送消息
                gameMsgPush.pushGameCancelMsgToUser(totalUids, gameEvent);
            }
        }
        // todo 为了保证我的比赛列表不再出现已经逻辑删除的比赛，暂时把 tb_game_event_team 表对应的参赛信息删除
        TbGameEventTeamExample example = new TbGameEventTeamExample();
        TbGameEventTeamExample.Criteria criteria = example.createCriteria();
        criteria.andGameEventIdEqualTo(gameEvent.getId());
        TbGameEventTeam tbGameEventTeam = new TbGameEventTeam();
        tbGameEventTeam.setIsDelete(GameConstants.IS_DELETE);
        tbGameEventTeamMapper.updateByExampleSelective(tbGameEventTeam,example);
    }

    @Override
    public RespUserGameTypeAndClub userClubMsgAndGameType(Integer uid) {
        RespUserGameTypeAndClub result = new RespUserGameTypeAndClub();
        Map<Integer, List<GameType>> paramGameType = new HashMap<>();
        GameType type = new GameType();
        type.setId(GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_PERSONAL.getId());
        type.setName(GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_PERSONAL.getLabel());
        List<GameType>  gameTypeList = new ArrayList<>();
        gameTypeList.add(type);
        paramGameType.put(GameConstants.CATEGORY_ID_BADMINTON, gameTypeList);
        List<GameType>  gameTypeList1 = new ArrayList<>();
        gameTypeList1.add(type);
        paramGameType.put(GameConstants.CATEGORY_ID_TENNIS, gameTypeList1);
        Map<Integer, List<RespClubAbstract>> temp1 = new HashMap<>();
        List<RespClubPlainInfo> clubs = baseService.getMyManageClubs(uid);
        logger.info("根据栏目分组俱乐部,所管理的俱乐部数目:"+clubs.size());
        if (CollectionUtils.isNotEmpty(clubs)) {
            for (RespClubPlainInfo club : clubs) {
                if (club.getClubTypeId() > 4 || club.getClubTypeId() < 1) continue;
                RespClubAbstract ab = new RespClubAbstract();
                ab.setClubId(club.getClubId());
                ab.setClubName(club.getClubName());
                List<RespClubAbstract> temp = temp1.get(club.getClubTypeId());
                if (CollectionUtils.isEmpty(temp)) {
                    temp = new ArrayList<>();
                }
                temp.add(ab);
                temp1.put(club.getClubTypeId(), temp);
            }
        }
        logger.info("根据用户权限分组赛事类型");
        for (int i = 1;i <= 4;i++) {
            List<RespClubAbstract> temp = temp1.get(i);
            if (CollectionUtils.isNotEmpty(temp)) {
                List<GameType>  gameTypeListT = paramGameType.get(i);
                if (null == gameTypeListT) {
                    gameTypeListT = new ArrayList<>();
                }
                GameType typeT = new GameType();

                if (GameConstants.CATEGORY_ID_BADMINTON == i) {
                    typeT.setId(GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_INTERNAL.getId());
                    typeT.setName(GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_INTERNAL.getLabel());
                }else if (GameConstants.CATEGORY_ID_BASKETBALL == i) {
                    typeT.setId(GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_BIG.getId());
                    typeT.setName(GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_BIG.getLabel());
                }else if (GameConstants.CATEGORY_ID_FOOTBALL == i) {
                    typeT.setId(GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_BIG.getId());
                    typeT.setName(GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_BIG.getLabel());
                }else if (GameConstants.CATEGORY_ID_TENNIS == i) {
                    typeT.setId(GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_INTERNAL.getId());
                    typeT.setName(GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_INTERNAL.getLabel());
                }
                gameTypeListT.add(typeT);
                paramGameType.put(i, gameTypeListT);
            }
        }
        result.setParamGameType(paramGameType);
        result.setParamClub(temp1);
        return result;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void generateRoundAndSchedule(TbGameEvent tbGameEvent, boolean isDouble, Integer uid, ReqGameRoundV2 gameRoundV2) throws Exception {

        /**
         * 生成轮次
         */
        List<GameRound> gameRoundList = new ArrayList<>();
        if(null != tbGameEvent) {
            gameRoundList = gameRoundService.createGameRound(tbGameEvent);
            if(null == gameRoundList){
                logger.error("当前赛事人数不足,无法生成对战表！赛事id：" + tbGameEvent.getId());
                throw new BizException(null, "当前赛事人数不足,无法生成对战表");
            }
        }

        /**
         * 生成对战表
         */
        if (isDouble) {
            List<TbGameEventTeam> tbGameEventTeamList = bizGameSystemDao.selectTbGameEventTeamByGameEventId(tbGameEvent.getId(), null, null, GameConstants.IS_NOT_DELETE);
            if (CollectionUtils.isEmpty(tbGameEventTeamList)) {
                throw new BizException(null, "当前赛事人数不足,无法生成对战表");
            }else {
                Collections.shuffle(tbGameEventTeamList);
                //8人抢签位\ 不固定打发不需要分组
                if (tbGameEvent.getGameSystemType().intValue() == GameSystemConfigEnum.CONFIG_GAME_TYPE_EIGHT_RULE.getId() ||
                        tbGameEvent.getGameSystemType().intValue() == GameSystemConfigEnum.CONFIG_GAME_TYPE_UNSET_RULE.getId()) {
                }else {
                    int n = tbGameEventTeamList.size()/2;
                    for (int i=0;i<n;i++) {
                        List<Integer> temp = new ArrayList<>();
                        temp.add(tbGameEventTeamList.get(i).getId());
                        temp.add(tbGameEventTeamList.get(n*2-1-i).getId());
                        bizGameOrderDao.insertTbTeamDoubleAddendum(tbGameEvent.getId(), temp);
                    }
                }
            }
        }
        if(null != gameRoundList && gameRoundList.size() > 0){
            ReqChallenge reqChallenge = new ReqChallenge();
            reqChallenge.setGameEventId(tbGameEvent.getId());
            reqChallenge.setGameRoundId(gameRoundList.get(0).getId());
            reqChallenge.setIsArrange((byte) 0);
            try {
                gameRoundService.generateCompListV2(reqChallenge);
            }catch (Exception e){
                logger.error("生产对战表失败！赛事id："+tbGameEvent.getId()+";轮次：" + gameRoundList.get(0).getId(),e);
                throw new BizException(null, "生产对战表失败！");
            }
        }
    }

    @Override
    public RespGameMember queryRespGameMember(Integer gameEventId, Integer uid) {
        TbGameEvent tbGameEvent = bizGameSystemDao.selectTbGameEvent(gameEventId);
        List<Integer> clubUids = baseService.getManageByClubId(tbGameEvent.getClubId());
        RespGameMember member = new RespGameMember();
        member.setIsAdmin(GameConstants.IS_NOT_DELETE);
        if (CollectionUtils.isNotEmpty(clubUids) && clubUids.contains(uid)) {
            member.setIsAdmin(GameConstants.IS_DELETE);
        }
        member.setId(tbGameEvent.getId());
        member.setGameSystem(gameEventTransfer.getGameSystemById(tbGameEvent.getGameSystemType().intValue()));
        member.setGameCategory(gameEventTransfer.getGameCategoryById(tbGameEvent.getGameCategoryType().intValue()));
        member.setCurrentUserList(queryJoinUser(gameEventId));
        member.setCurrentGameRoundId(tbGameEvent.getCurrentRoundId());
        member.setIsVisible(tbGameEvent.getIsVisible());
        member.setLimitNum(tbGameEvent.getTeamLimitNum());
        member.setClubId(tbGameEvent.getClubId());
        return member;
    }

    @Override
    public ClubGameEventConfig getClubGameEventConfig(Integer uid) {
        ClubGameEventConfig clubGameEventConfig = officialGameCache.getClubGameEventConfig();
        if(null == clubGameEventConfig || null == clubGameEventConfig.getCityInfosList()
                || clubGameEventConfig.getCityInfosList().size() == 0){
            clubGameEventConfig = new ClubGameEventConfig();
            //城市区域
            clubGameEventConfig.setCityInfosList(initRespCityInfoList());

            List<GameType> bigBallGameTypeConfigList = new ArrayList<>();
            bigBallGameTypeConfigList.add(new GameType(-1, "全部"));

            List<GameType> gameTypeConfigList = new ArrayList<>();
            gameTypeConfigList.add(new GameType(-1, "全部"));
            gameTypeConfigList.add(new GameType(GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_NGKC.getId(), GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_NGKC.getLabel()));
            gameTypeConfigList.add(new GameType(GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_PERSONAL.getId(), GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_PERSONAL.getLabel()));
            gameTypeConfigList.add(new GameType(GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_INTERNAL.getId(), GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_INTERNAL.getLabel()));
            gameTypeConfigList.add(new GameType(GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_SCENE.getId(), GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_SCENE.getLabel()));

            // 栏目
            List<GameCategoryInfo> categoryInfoList = new ArrayList<>();
            categoryInfoList.add(new GameCategoryInfo(0, "全部"));
            categoryInfoList.add(new GameCategoryInfo(GameConstants.CATEGORY_ID_BASKETBALL, "篮球", bigBallGameTypeConfigList));
            categoryInfoList.add(new GameCategoryInfo(GameConstants.CATEGORY_ID_BADMINTON, "羽毛球", gameTypeConfigList));
            categoryInfoList.add(new GameCategoryInfo(GameConstants.CATEGORY_ID_FOOTBALL, "足球", bigBallGameTypeConfigList));
            categoryInfoList.add(new GameCategoryInfo(GameConstants.CATEGORY_ID_TENNIS, "网球", gameTypeConfigList));
            clubGameEventConfig.setCategoryList(categoryInfoList);

            //时间
            List<GameEventConfigTime> timeList = new ArrayList<>();
            timeList.add(new GameEventConfigTime(-1, "全部"));
            timeList.add(new GameEventConfigTime(0, "今天"));
            timeList.add(new GameEventConfigTime(1, "明天"));
            timeList.add(new GameEventConfigTime(2, "后天"));
            timeList.add(new GameEventConfigTime(3, "三天后"));

            clubGameEventConfig.setTimeList(timeList);

            logger.info("getClubGameEventConfig clubGameEventConfig:"+clubGameEventConfig.toString());

            //缓存redis
            officialGameCache.initClubGameEventConfig(clubGameEventConfig);
        }

        try{
            List<RespClubPlainInfo> list = baseService.getMyManageClubs(uid.intValue());
            int clubAdmin = 0;
            if (null != list && list.size() > 0){
                logger.info("getClubGameEventConfig list:"+ list.size());
                for (RespClubPlainInfo clubPlainInfo: list) {
                    if (clubPlainInfo.getClubTypeId() == GameConstants.CATEGORY_ID_BADMINTON || clubPlainInfo.getClubTypeId() == GameConstants.CATEGORY_ID_TENNIS ) {
                        clubAdmin = 1;
                    }
                }
            }

            clubGameEventConfig.setClubAdmin(clubAdmin);
        }catch (Exception e) {
            logger.error("ClubGameEventConfig exception:", e);
        }

        return clubGameEventConfig;
    }

    @Override
    public List<GameEvent> queryClubGameEventList(ReqClubGameEvent reqClubGameEvent) {
        Map<String, Object> parmMap = new HashMap<>();
        if (-1 == reqClubGameEvent.getCityId()) {
            reqClubGameEvent.setCityId(0);
        }

        parmMap.put("cityId", reqClubGameEvent.getCityId());

        if (null!= reqClubGameEvent.getDistrictId() && reqClubGameEvent.getDistrictId() != 0) {
            parmMap.put("districtId", reqClubGameEvent.getDistrictId());
        }

        if (reqClubGameEvent.getCategoryId() != 0) {
            parmMap.put("categoryId", reqClubGameEvent.getCategoryId());
        }

        if (null != reqClubGameEvent.getGameType() && reqClubGameEvent.getGameType() > -1) {
            parmMap.put("gameType", reqClubGameEvent.getGameType().byteValue());
        }

        if (null != reqClubGameEvent.getTime() && reqClubGameEvent.getTime().intValue() > -1){
            Map <String, Date> timeMap = changeTime(reqClubGameEvent.getTime().intValue());
            parmMap.put("startTime", timeMap.get("startTime"));
            logger.info("queryClubGameEventList startTime:"+timeMap.get("startTime")+" currentTimeMillis:"+System.currentTimeMillis());

            if (reqClubGameEvent.getTime().intValue() != 3) {
                parmMap.put("endTime", timeMap.get("endTime"));
                logger.info("queryClubGameEventList endTime:"+timeMap.get("endTime")+" currentTimeMillis:"+System.currentTimeMillis());
            }
        }

        parmMap.put("pageNo", reqClubGameEvent.getPageNo());
        parmMap.put("pageSize", reqClubGameEvent.getPageSize());

        logger.info("queryClubGameEventList parmMap:"+ parmMap);

        List<TbGameEvent> tbGameEventList = bizGameSystemDao.selectTbGameEventList(parmMap);
        List<Integer> gameEventIdList = new ArrayList<>();
        for (TbGameEvent tbGameEvent : tbGameEventList) {
                gameEventIdList.add(tbGameEvent.getId());
        }

        return changTbGameEvent(gameEventIdList, reqClubGameEvent);
    }

    @Override
    public List<GameEvent> queryUidClubGameEventList(ReqClubGameEvent reqClubGameEvent) {

        List<GameEvent> gameEventList = Collections.emptyList();
        try{

            // 我的比赛只显示用户参与的    特此修改（与文泰确认）
//            List<Integer> clubs = new ArrayList<>();
//            List<RespClubPlainInfo> list = baseService.getMyManageClubs(reqClubGameEvent.getUid().intValue());
//            if (null != list && list.size() > 0){
//                for (RespClubPlainInfo respClubPlainInfo : list) {
//                    clubs.add(respClubPlainInfo.getClubId());
//                }
//            }

            List<TbGameEventTeam> tbGameEventTeamList = bizGameSystemDao.selectUidTbGameEventList(reqClubGameEvent.getUid(), reqClubGameEvent.getPageNo(), reqClubGameEvent.getPageSize());

            if (null != tbGameEventTeamList) {
                logger.info("queryUidClubGameEventList tbGameEventList:" + tbGameEventTeamList.size());
            }

            List<Integer> gameEventIdList = new ArrayList<>();
            for (TbGameEventTeam tbGameEventTeam : tbGameEventTeamList) {
                gameEventIdList.add(tbGameEventTeam.getGameEventId());
            }

            gameEventList = changTbGameEvent(gameEventIdList, reqClubGameEvent);
        }catch (Exception e) {
            logger.error("queryUidClubGameEventList exception:", e);
        }

        return gameEventList;
    }

    /**
     * 初始化区域位置
     * */
    private RespDistrict initRespDistrict(Double lat, Double lng, Integer placeId){
        RespDistrict respDistrict = new RespDistrict();
        if (null!=lat && lat >0 && null!=lng && lng > 0) {
            respDistrict.setLat(lat);
            respDistrict.setLng(lng);
            RespDistrict temp = baseService.getRespDistrictByLatAndLng(lat, lng);
            respDistrict.setCityId(6);
            respDistrict.setId(0);
            if (null!=temp) {
                if (null!=temp.getCityId()) {
                    respDistrict.setCityId(temp.getCityId());
                }
                if (null!=temp.getId()) {
                    respDistrict.setId(temp.getId());
                }
            }
        }else {
            List<Integer> placeIds = new ArrayList<>();
            placeIds.add(placeId);
            Map<Integer, PlaceInfo> map = baseService.queryPlaceInfoMsgList(placeIds);
            if (null!=map && map.size()>0) {
                PlaceInfo placeInfo = map.get(placeId);
                if (null!=placeInfo && placeInfo.getPlaceId() >0){
                    respDistrict.setId(placeInfo.getDistrictId());
                    respDistrict.setCityId(placeInfo.getCityId());
                    respDistrict.setLat(placeInfo.getLat());
                    respDistrict.setLng(placeInfo.getLng());
                }
            }
        }
        return respDistrict;
    }

    private List<RespCityInfos> initRespCityInfoList() {
        List<RespCityInfos> cityInfosList = Collections.emptyList();
        try{
            cityInfosList = baseService.queryRespCityInfos();
            List<RespDistrict> districtList;
            RespDistrict respDistrict;
            if (ObjectUtil.isNotObjectEmpty(cityInfosList) && cityInfosList.size() > 0 ) {
                for (RespCityInfos respCityInfos : cityInfosList) {
                    respDistrict = new RespDistrict();
                    respDistrict.setId(0);
                    respDistrict.setCityId(respCityInfos.getRespCity().getId());
                    respDistrict.setName("全" + respCityInfos.getRespCity().getName());

                    districtList = new ArrayList<>();
                    districtList.add(0, respDistrict);
                    districtList.addAll(respCityInfos.getRespDistrict());
                    respCityInfos.setRespDistrict(districtList);
                }

                RespCityInfos cityInfos = new RespCityInfos();
                RespCity respCity = new RespCity();
                respCity.setId(-1);
                respCity.setName("其他");
                cityInfos.setRespCity(respCity);

                respDistrict = new RespDistrict();
                respDistrict.setId(0);
                respDistrict.setCityId(respCity.getId());
                respDistrict.setName("全部");

                districtList = new ArrayList<>();
                districtList.add(0, respDistrict);
                cityInfos.setRespDistrict(districtList);
                cityInfosList.add(cityInfos);
            }
        } catch (Exception e){
            logger.error("initRespDistrictConfig exception:", e);
        }
        return cityInfosList;
    }

    private List<GameEvent> changTbGameEvent(List<Integer> gameEventIdList, ReqClubGameEvent reqClubGameEvent){
        List<GameEvent> gameEventList = Collections.emptyList();

        if(ObjectUtil.isObjectEmpty(gameEventIdList) || gameEventIdList.size() == 0) {
            logger.info("changeListTbGameEvent tbGameEventList is null.");
            return gameEventList;
        }

        gameEventList = new ArrayList<>();
        try {
            for (Integer gameEventId : gameEventIdList) {
                gameEventList.add(initGameEvent(gameEventId, reqClubGameEvent.getUid()));
            }
        } catch (Exception e) {
            logger.error("changeListTbGameEvent exception info:", e);
        }

        return gameEventList;
    }

    private GameEvent initGameEvent(Integer gameEventId, Integer uid) {
        GameEvent gameEvent = null;
        try {
            gameEvent = officialGameCache.getGameEvent(gameEventId);
            gameEvent.setCurTime(new Date().getTime());

            boolean flag = false;

            if (uid.intValue() > 0) {
                List<Integer> userJoinedGameEventIds = gameEventService.userGameEventIds(uid, gameEvent.getCategoryId());
                if (null == userJoinedGameEventIds) {
                    //用户报名参加的赛事(大球类,或者小球类)
                    if (null != userJoinedGameEventIds && userJoinedGameEventIds.size() > 0) {
                        flag = true;
                    }
                }

                if (flag && userJoinedGameEventIds.contains(gameEvent.getId())) {
                    gameEvent.setIsJoin((byte) 1);
                }
            }
        } catch (Exception e) {
            logger.error("initGameEvent exception:", e);
        }

        return gameEvent;
    }

    private Map<String, Date> changeTime(int time) {
        Map<String, Date> map = new HashMap<>();
        long dayLong = 24*60*60*1000;
        map.put("startTime", new Date(getStartTime() + time * dayLong));
        map.put("endTime", new Date(getEndTime() + time * dayLong));

        return map;
    }

    private long getStartTime(){
        Calendar todayStart = Calendar.getInstance();
        todayStart.set(Calendar.HOUR, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);
        todayStart.set(Calendar.MILLISECOND, 0);
        return todayStart.getTime().getTime();
    }

    private long getEndTime(){
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.set(Calendar.HOUR, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        todayEnd.set(Calendar.MILLISECOND, 999);
        return todayEnd.getTime().getTime();
    }
}
